<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Msite extends Controller_Template
{
    private $_version = '1.2.18';

    public function __construct ($request, $response)
    {
        $this->template = 'smarty:msite/index';
        parent::__construct($request, $response);
    }
    
    public function action_list($type = null){
        $types = array(
            'index'        => 'index',
            'soft'         => 'soft',
            'game'         => 'game',
            'top'          => 'top',
            'strategylist' => 'strategylist',
            'newrecommend' => 'newrecommend',
            'tag_list'     => 'tag_list'
        );
        if(empty($type) || !in_array($type, array_keys($types))){
            $this->request->redirect('/index');
        }else{
             $this->request->redirect("/{$types[$type]}");
        }
    }

    public function action_index($page = 1)
    {
        
        $pagesize = 30;
        $start = $pagesize * (max(1, $page) - 1);

        //banner
        $banner_list = API_Market::banner_list(5);
        //编辑推荐
        $channel    = self::channel();
        $list       = API_Market::feature_list($start, $pagesize, $channel);
        $next_page  = $this->next_page($list['total'], $pagesize, $page);

        $this->template->set('list', $list);
        $this->ajax_list_output($list, $next_page);
        $this->template->set('next_page', $next_page);
        $this->template->set('banner_list', $banner_list);
        $this->template->set_filename('smarty:msite/index');
    }

    public function action_soft($catid = '', $page = 1)
    {
        
        $category = API_Market::app_category();
        if (empty($catid) || empty($category['children'][$catid]['name']))
        {
            $catid = Arr::get($category, 'id', 30);
            $catename = "全部分类";
            $this->template->set_filename('smarty:msite/all_category');
            $this->template->set('type', array('key' => 'soft', 'cateid' => $catid));
            $this->template->set('items', API_Category::items($catid));
        }
        else
        {
            $catename = $category['children'][$catid]['name'];
            $this->lists($catid, $page);
            $this->template->set('catid', $catid);
            $this->template->set('category', $category);
            $this->template->set('catename', $catename);
        }
    }

    public function action_game($catid = '', $page = 1)
    {
        
        $category = API_Market::game_category();
        if (empty($catid) || empty($category['children'][$catid]['name']))
        {
            $catid = Arr::get($category, 'id', 40);
            $catename = "全部分类";
            $this->template->set_filename('smarty:msite/all_category');
            $this->template->set('type', array('key' => 'game', 'cateid' => $catid));
            $this->template->set('items', API_Category::items($catid));
        }
        else
        {
            $catename = $category['children'][$catid]['name'];
            $this->lists($catid, $page);
            $this->template->set('catid', $catid);
            $this->template->set('category', $category);
            $this->template->set('catename', $catename);
        }
    }

    public function action_newrecommend($page = 1)
    {
        
        $pagesize = 20;
        $start = $pagesize * (max(1, $page) - 1);

        $list = API_Market::newrecommend_list($start, $pagesize);
        $next_page = $this->next_page($list['total'], $pagesize, $page);
        foreach ($list['list'] as &$app) {
            if($app['closeDownload']) {
                $app['apkUrl'] = 'javascript:;';
            }
            if($app['packageName'] == 'com.baidu.appsearch') {
                $app['closeDownload'] = TRUE;
                $app['closeDownloadTips'] = '抱歉，暂时停止提供下载';
                $app['apkUrl'] = 'javascript:;';
            }
        }

        $this->template->set_filename('smarty:msite/newrecommend');
        $this->template->set('list', $list);
        $this->ajax_list_output($list, $next_page);        
        $this->template->set('next_page', $next_page);
    }

    public function action_search($keyword = '', $page = 1)
    {
        $pagesize = 20;
        $keyword = trim($keyword);
        $start = $pagesize * (max(1, $page) - 1);

        if (empty($keyword))
        {

            $hot_search_words = API_Market::hot_search_words(15);
            $this->template->set('words', $hot_search_words);
            $this->template->set_filename('smarty:msite/search_empty');
            return;
        }

        $list = API_Market::search($keyword, $start, $pagesize);
        $next_page = $this->next_page($list['total'], $pagesize, $page, $keyword);

        $hot_search_words = API_Market::hot_search_words(10);


        $this->template->set('list', $list);
        $this->ajax_list_output($list, $next_page);        
        $this->template->set('keyword', $keyword);
        $this->template->set('next_page', $next_page);
        $this->template->set('hot_search_words', $hot_search_words);
        $this->template->set_filename('smarty:msite/search');
    }

    public function action_mydownloads ()
    {
        $this->template->set_filename('smarty:msite/mydownloads');
    }

    public function action_top($type = 'soft', $page = 1)
    {
        $type_arr = array('soft' => '软件榜', 'game' => '游戏榜');
        $type = isset($type_arr[$type]) ? $type : 'soft';
        $pagesize = 20;
        $start = $pagesize * (max(1, $page) - 1);

        $list = API_Market::toplist('popular_'.$type, $start, $pagesize);
        $next_page = $this->next_page($list['total'], $pagesize, $page, $type);


        $this->template->set('type', $type);
        $this->template->set('list', $list);
        $this->ajax_list_output($list, $next_page);        
        $this->template->set('next_page', $next_page);
        $this->template->set_filename('smarty:msite/top');
    }

    public function action_pop($type = 'soft', $page = 1)
    {
        $type_arr = array('soft' => '流行应用', 'game' => '流行游戏');
        $type = isset($type_arr[$type]) ? $type : 'soft';
        $pagesize = 20;
        $start = $pagesize * (max(1, $page) - 1);

        $list = API_Market::toplist('want_'.$type, $start, $pagesize);
        $next_page = $this->next_page($list['total'], $pagesize, $page, $type);


        $this->template->set('type', $type);
        $this->template->set('list', $list);
        $this->ajax_list_output($list, $next_page);        
        $this->template->set('next_page', $next_page);
        $this->template->set_filename('smarty:msite/pop');
    }


    public function action_app($packagename = '')
    {
        if(empty($packagename)) 
            throw new HTTP_Exception_404();

        if (is_numeric($packagename))
        {
            $this->request->redirect('/app/'.$info['packageName'], 301, false);
            exit;
        }
 
        $this->template->set_filename('smarty:msite/app');
        $info = API_Market::appinfo($packagename);
        if (empty($info))
            throw new HTTP_Exception_404();
       
        $comment_list = API_Market::comment_list(Arr::get($info, 'blockId', 0), 0, 10);
        $info['description'] = nl2br(Arr::get($info, 'description'));
        $info['updateMsg'] = nl2br(Arr::get($info, 'updateMsg'));

        $this->template->set('info', $info);
        $this->template->set('comment_list', $comment_list);
    }

    public function action_strategylist($packagename = '', $page = 1)
    {
        $pagesize = 20;

        if (is_numeric($packagename))
        {
            $page = $packagename;
            $packagename = '';
        }
        $start = $pagesize * (max(1, $page) - 1);
        $strategylist = API_Strategy::strategylist($start, $pagesize, $packagename);

        if(!empty($packagename))
        {
            $info = API_Market::appinfo($packagename);
            $this->template->set('info', $info);
        }

        $next_page = $this->next_page($strategylist['total'], $pagesize, $page, $packagename);

        
        $this->template->set('next_page', $next_page);
        $this->template->set('strategylist', $strategylist);
        $this->ajax_strategy_list_output($strategylist, $next_page);
        $this->template->set_filename('smarty:msite/strategy_list');
    }

    public function action_strategy($appId = '',$id = '')
    {
        if(empty($appId) || empty($id))
        {
            throw new HTTP_Exception_404();
        }

        $this->template->set_filename('smarty:msite/strategy');

        $strategyinfo = API_Strategy::strategyinfo($appId, $id);

        if(!empty($strategyinfo['packageName']))
        {
            $info = API_Market::appinfo($strategyinfo['packageName']);
            $strategylist = API_Strategy::strategylist(0, 5, $strategyinfo['packageName']);
            $info['description'] = nl2br(Arr::get($info, 'description'));
            $info['updateMsg'] = nl2br(Arr::get($info, 'updateMsg'));
            $comment_list = API_Market::comment_list(Arr::get($info, 'id', 0), 0, 10);

            $this->template->set('info', $info);
            $this->template->set('comment_list', $comment_list);
            $this->template->set('strategylist', $strategylist);
        }else {
            //throw new HTTP_Exception_404();
        }

        $shortdes = str_replace(array(' ', '　'), '', mb_substr(strip_tags(Arr::get($strategyinfo, 'content')),0,30)). '...';

        $this->template->set('strategyinfo', $strategyinfo);
        $this->template->set('shortdes', $shortdes);
    }

    public function action_down($packagename = '', $channel = '')
    {
        if (empty($channel))
        {
            $channel = self::channel();
        }
        //应用汇版本号
        $yyh_version = $this->yyh_version();
        $session_id = Session::instance()->id();
        //应用下载规则
        $download_config = Kohana::config('download.channel');
        $channel_download = Arr::get($download_config, $channel, Arr::get($download_config, 'default'));
        $download_url = Arr::get($channel_download, $packagename, Arr::get($channel_download, 'default'));
        if (empty($download_url))
        {
            $info = API_Market::appinfo($packagename);
            $download_url = empty($info) ? '/' : $info['apkUrl'].'/?channel='.$channel.'&uid='.$session_id;
        }
        else
        {
            $download_url = str_replace(array('{channel}', '{yyh_version}', '{session_id}', '{packagename}'), array($channel, $yyh_version, $session_id, $packagename), $download_url);
        }

        if($packagename == 'com.yingyonghui.market') {
            $download_channel = 'ac.publish.'.$channel.'.02';
        } else {
            $download_channel = 'ac.publish.'.$channel.'.01';
        }
        $this->log('download', $download_channel);

        $this->request->redirect($download_url);
    }

    public function action_download($packagename = '')
    {
        if (substr($packagename, -4) == '.apk')
        {
            $packagename = substr($packagename, 0, -4);
        }
        if ($packagename == 'com.wsandroid.suite')
        {
            $this->request->redirect('http://mobile.appchina.com/market/e/2075676/0/0/0/1402295609739/package_310001.1402295609739?channel=msite');
        }
        else
        {
            $this->action_down($packagename);
        }
    }

    public function action_cache_admin()
    {
        if (!$this->is_login())
        {
            Header("WWW-Authenticate: Basic realm=\"Cache Admin Login\"");
            Header("HTTP/1.0 401 Unauthorized");
            exit;
        }
        Session::instance()->set('cache_admin', true);
        $this->request->redirect('/');
    }

    public function action_tag_list()
    {
        $all_tag_list = API_WWW::getTagList();
        
        $this->template->set('all_tag_list',$all_tag_list);
        $this->template->set_filename('smarty:msite/tag_list');
    }

    public function action_tag($keyword = '', $page = 1)
    {
        $pagesize = 15;
        $keyword = trim($keyword);
        $start = $pagesize * (max(1, $page) - 1);
        if( !$this->is_in_tag_list($keyword) ) {
            return ;
            //throw new HTTP_Exception_404();
        }
        $list = API_Market::search($keyword, $start, $pagesize);
        $next_page = $this->next_page($list['total'], $pagesize, $page, $keyword);

        if($list['total'] >= 300) {
            $list['total'] = 300;
        }


        $taglist = API_WWW::getHotTag(0,15);


        $this->template->set('list', $list);
        $this->ajax_list_output($list, $next_page);        
        $this->template->set('tag', $keyword);
        $this->template->set('next_page', $next_page);
        $this->template->set('hot_search_words', $taglist);
        $this->template->set_filename('smarty:msite/tag');
    }

    public function before()
    {
        parent::before();
        if($this->request->action() != 'down') {
            $this->log('view');
        }
        //清除缓存
        if (Arr::get($this->request->query(), 'nocache'))
        {
            API_Market::$cache_status = false;
        }
        $this->launch();

        $this->template->set('param', $this->request->param());
        $this->template->set('action', $this->request->action());
        $this->template->set('channel', $this->channel());
        $this->template->set('sessionid', Session::instance()->id());
        $this->template->set('version', $this->_version);
        $this->template->set('adpackagename', 'http://mp.weixin.qq.com/s?__biz=MTE4OTMwNzk4MQ==&mid=202438766&idx=1&sn=26ff1f4be7a3d8bd51f1cb78495fc2d7#rd');
        $this->template->set('p', $this->request->query('p'));

        return true;
    }

    public function action_api ($type)
    {
        $post = $this->request->post();
        $ret  = array();

        if ($type == 'upgrade')
        {
            $apps = array();
            foreach ($post as $key => $val)
            {
                list($pName, $iCode) = explode('|', $val);
                $apps[$pName] = $iCode;
            }
            $result = API_Package::getUpgradePackages($apps);
            $ret = array('status' => 0, 'result' => $result);
        }
        else if ($type == 'check_update_market')
        {
            $ret = array('status' => 0, 'versionCode' => 200, 'versionName' => '2.0.0', 'apkUrl' => 'http://app.ixindong.cn/upload/upgrade/market_v200.apk');
        }

        echo json_encode($ret);
        exit;
    }

    //获取渠道信息
    private function channel()
    {
        return 'm.cherry';
        $channel = $this->request->query('channel');
        if (!empty($channel) && (in_array(substr($channel, 0, 11), array('ac.union.m_', 'ac.union.m.')) || in_array(substr($channel, 0, 12), array('ac.union.bd_', 'ac.union.bd.')) || in_array($channel, Kohana::config('channel.allow_channel'))))
        {
            Session::instance()->set('channel', $channel);
        }
        else
        {
            $channel = Session::instance()->get('channel');
            if (empty($channel))
            {
                $client_ip = Tools_IP::get_client_ip();
                if (Tools_IP::is_taiwan($client_ip))
                {
                    $channel = 'm.tw.'.$this->referer_type();
                    Session::instance()->set('channel', $channel);
                }
                else
                {
                    $channel = 'm.cherry';
                }
            }
        }
        return $channel;
    }

    private function lists($catid, $page)
    {
        $pagesize = 20;
        $start = $pagesize * (max(1, $page) - 1);

        $list = API_Market::app_list($catid, $start, $pagesize);
        $next_page = $this->next_page($list['total'], $pagesize, $page, $catid);
        
        $this->template->set('catid', $catid);
        $this->template->set('list', $list);
        $this->ajax_list_output($list, $next_page);
        $this->template->set('next_page', $next_page);
        $this->template->set_filename('smarty:msite/list');
    }

    private function next_page($total, $pagesize, $page, $param = '')
    {
        $total_pages = ceil($total / $pagesize);
        if ($page >= $total_pages) return '';
        return '/index.php/'.$this->request->action().($param ? '/'.$param : '').'/'.($page+1);
    }

    private function ajax_list_output($list, $next_page)
    {
        if ($this->request->is_ajax())
        {
            $this->template->set_filename('smarty:msite/ajax_list');
            
            $data['list']       = $this->template->render();
            $data['next_page']  = $next_page;
            $this->json($data);
        }
    }
    private function ajax_strategy_list_output($list, $next_page)
    {
        if ($this->request->is_ajax())
        {
            $this->template->set_filename('smarty:msite/ajax_strategy_list');
            
            $data['list']       = $this->template->render();
            $data['next_page']  = $next_page;
            $this->json($data);
        }
    }

    private function json($data)
    {
        echo json_encode($data);
        exit;
    }

    private function is_login()
    {
        $ADMIN_USERNAME = 'da';
        $ADMIN_PASSWORD = 'data@yyh!!';
        return isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])
        && $_SERVER['PHP_AUTH_USER'] == $ADMIN_USERNAME && $_SERVER['PHP_AUTH_PW'] == $ADMIN_PASSWORD;
    }

    private function yyh_version()
    {
        $cache = Cache::instance('memcache');
        $cache_key = 'msite_yyh_version';
        $yyh_version = $cache->get($cache_key);
        if (empty($yyh_version) || ($this->is_login() && !empty($_GET['nocache'])))
        {
            //取最新版本号
            API_Market::$cache_status = false;
            $info = API_Market::appinfo('com.yingyonghui.market');
            $yyh_version = Arr::get($info, 'versionCode', '');
            $cache->set($cache_key, $yyh_version, 600);
        }
        return $yyh_version;
    }

    private function launch()
    {
        $cache = Cache::instance('memcache');
        $cache_key = 'market_api_launch';
        if (!$cache->get($cache_key))
        {
            API_Market::launch();
            $cache->set($cache_key, 1, 86400);
        }
    }

    private function is_in_tag_list($tag_name) {

        $cache = Cache::instance('memcache');
        $data = $cache->get('tag_name_list');
        if (empty($data))
        {
            $taglist = API_WWW::getTagList();
            for($i = 0;$i < 8; $i++) {
                foreach ( $taglist['data'][$i] as $tag ) {
                    $data[ $tag['name'] ] = '1';
                }            
            }
            $cache->set('tag_name_list', $data);
        }

        if( isset($data[$tag_name]) ){
            return TRUE;
        } else {
            return FALSE;
        }
    }

    //记录来源[百度，谷歌，其它]
    private function referer_type()
    {
        $type = 'qt';//其它
        if(empty($_SERVER['HTTP_REFERER']))
        {
            
        }
        else if(strpos($_SERVER['HTTP_REFERER'], 'm.baidu.com') || strpos($_SERVER['HTTP_REFERER'], 'www.baidu.com'))
        {
            $type = 'bd';
        }
        else if(strpos($_SERVER['HTTP_REFERER'], 'www.google.'))
        {
            $type = 'gg';
        }
        return $type;
    }
    
    private function log( $type, $channel1 = '') {
        $channel = $this->channel();
        if(substr($channel,0,4) == 'm.tw') {
            if(empty($channel1)) {
                $log['channel']   = $channel; 
            } else {
                $log['channel']   = $channel1;
            }
            $log['sessionid']     = Session::instance()->id();
            $log['type']          = $type;
            $log['ip']            = Tools_IP::get_client_ip();
            $log['url']           = $_SERVER['REQUEST_URI'];

            kohana::$log->add(Log::DEBUG, 'TW_STAT|'.json_encode($log) );
        }
    }    
    
}
